<template>
  <div class="comment-list-container">
    <div v-if="comments.length === 0 && !loading" class="empty-comments">
      <el-empty description="暂无评论，快来抢沙发吧！" :image-size="80"></el-empty>
    </div>

    <div v-for="comment in comments" :key="comment._id" class="comment-item">
      <comment-display
        :comment="comment"
        :current-user-id="currentUser?._id"
        @reply="handleReply"
        @edit="handleEdit"
        @delete="handleDelete"
        @toggle-like="handleToggleLike"
      />

      <!-- 回复输入框 -->
      <add-comment
        v-if="replyingTo === comment._id"
        ref="addCommentRef"
        :targetId="comment.targetId"
        :targetType="comment.targetType"
        :parentId="comment._id"
        :replyToUser="comment.user"
        @comment-added="handleReplyAdded"
        @cancel-reply="cancelReply"
        class="reply-input"
      />

      <!-- 子评论/回复列表 -->
      <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
         <!-- 可以添加展开/收起回复的逻辑 -->
        <div v-for="reply in comment.replies" :key="reply._id" class="comment-item reply-item">
          <comment-display
            :comment="reply"
            :current-user-id="currentUser?._id"
            @reply="handleReply"
            @edit="handleEdit"
            @delete="handleDelete"
            @toggle-like="handleToggleLike"
          />
          <!-- 二级回复输入框 -->
          <add-comment
            v-if="replyingTo === reply._id"
            ref="addCommentRef"
            :targetId="reply.targetId"
            :targetType="reply.targetType"
            :parentId="reply._id" 
            :replyToUser="reply.user"
            @comment-added="handleReplyAdded"
            @cancel-reply="cancelReply"
            class="reply-input"
          />
           <!-- 可以递归显示更多层级的回复，但通常建议限制层级 -->
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore && !loading" class="load-more-comments">
      <el-button @click="emit('load-more')" :loading="loading">加载更多评论</el-button>
    </div>
    <div v-if="loading" class="loading-indicator">
      <el-icon class="is-loading"><Loading /></el-icon> 正在加载...
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, defineAsyncComponent } from 'vue';
import { useStore } from 'vuex';
import axios from '@/services/axios'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

// 异步加载 AddComment 组件，避免循环依赖
const AddComment = defineAsyncComponent(() => import('./AddComment.vue'));
// 异步加载 CommentDisplay 组件
const CommentDisplay = defineAsyncComponent(() => import('./CommentDisplay.vue'));

const props = defineProps({
  comments: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  hasMore: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['load-more', 'reply-added', 'comment-updated', 'comment-deleted', 'like-toggled']);

const store = useStore();
const replyingTo = ref(null); // 正在回复的评论 ID
const editingComment = ref(null); // 正在编辑的评论
const addCommentRef = ref(null); // 引用 AddComment 组件实例

// 修正 currentUser 的获取方式
const currentUser = computed(() => store.state.auth.user);

// 处理点击回复按钮
const handleReply = (comment) => {
  replyingTo.value = comment._id;
  // 确保 AddComment 组件渲染完成后再聚焦
  nextTick(() => {
    // 使用 ref 获取当前活动的回复框组件
    const replyInputs = document.querySelectorAll('.reply-input');
    replyInputs.forEach(el => {
      const component = el.__vueParentComponent?.ctx;
      if (component?.focusInput) {
        component.focusInput();
      }
    });
  });
};

// 处理回复成功
const handleReplyAdded = (newReply) => {
  emit('reply-added', newReply, newReply.parentId);
  replyingTo.value = null; // 关闭回复框
};

// 取消回复
const cancelReply = () => {
  replyingTo.value = null;
};

// 处理编辑评论 (CommentDisplay 中实现编辑状态切换和保存)
const handleEdit = (comment) => {
    // CommentDisplay 内部处理编辑逻辑，完成后触发 comment-updated
    // 这里可以预留接口，例如记录正在编辑的评论 ID
    editingComment.value = comment;
};

// 处理删除评论
const handleDelete = async (comment) => {
  ElMessageBox.confirm('确定要删除这条评论吗？子评论也会被一并删除。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/comments/${comment._id}`);
      ElMessage.success('评论删除成功');
      emit('comment-deleted', comment._id);
    } catch (error) {
      console.error('删除评论失败:', error);
      ElMessage.error(error.response?.data?.error || '删除评论失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 处理切换评论点赞
const handleToggleLike = async (comment) => {
  if (!currentUser.value?._id) {
      ElMessage.warning('请登录后操作');
      return;
  }
  // Find the comment or reply in the local list to update its liking state temporarily
  const findAndUpdateLikingState = (list, id, likingState) => {
      for (let item of list) {
          if (item._id === id) {
              item.liking = likingState; // Add a temporary 'liking' state
              return true;
          }
          if (item.replies && findAndUpdateLikingState(item.replies, id, likingState)) {
              return true;
          }
      }
      return false;
  };

  findAndUpdateLikingState(props.comments, comment._id, true);

  try {
    // Call the API directly
    const response = await axios.post(`/api/comments/${comment._id}/like`);
    // Emit the event with updated data from the API response
    emit('like-toggled', { commentId: comment._id, isLiked: response.data.isLiked, likesCount: response.data.likesCount });
  } catch (error) {
    console.error('点赞/取消点赞评论失败:', error);
    ElMessage.error(error.response?.data?.error || '操作失败');
    // Revert the temporary liking state on error if needed, though the parent update should handle it
  } finally {
      findAndUpdateLikingState(props.comments, comment._id, false); // Remove temporary state
  }
};
</script>

<style scoped>
.comment-list-container {
  margin-top: 20px;
}

.empty-comments {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.comment-item {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.comment-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.replies-list {
  margin-left: 52px; /* 与头像+间距宽度一致 */
  margin-top: 15px;
  border-left: 2px solid #e0e0e0;
  padding-left: 15px;
}

.reply-item {
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px dashed #f0f0f0; /* 子评论用虚线分隔 */
}
.reply-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.reply-input {
    margin-left: 52px; /* 与头像+间距宽度一致 */
    margin-top: 10px;
}

.load-more-comments {
  text-align: center;
  margin-top: 20px;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #909399;
}
.loading-indicator .el-icon {
  margin-right: 5px;
}
</style>